package cn.flying.base.web.auth.handler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;

import cn.flying.base.common.enums.RtCodeEnum;
import cn.flying.base.common.vo.Rt;
import cn.flying.base.core.common.utils.Ft;
import cn.flying.base.web.auth.configuration.LoginUser;
import cn.flying.base.web.auth.domain.SysLoginLog;
import cn.flying.base.web.auth.service.SysUserService;

/**
 * @description: 登出成功处理类
 * @author: lvyong
 * @date: 2023年05月27日 10:47
 * @version: 1.0
 */
@Component
public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private SysUserService sysUserService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取当登录用户信息
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        logger.info("租户【{}】的用户【{}-{}】退出系统登录成功！", loginUser.getTenantId(), loginUser.getUserId(), loginUser.getUsername());

        try {
            //保存登录日志
            SysLoginLog loginLog = new SysLoginLog();
            loginLog.setUserId(loginUser.getUserId());
            loginLog.setUserName(loginUser.getUsername());
            loginLog.setName(loginUser.getName());
            //I 登入成功 O 登出成功  F 登入失败  T 会话失效
            loginLog.setHappenType("O");
            loginLog.setHappenTime(new Date());
            loginLog.setHappenIp(Ft.Network.getIpAddress(request));
            loginLog.setRemark("用户成功退出系统");
            loginLog.setTenantId(loginUser.getTenantId());
            loginLog.setCreatedBy(loginUser.getUsername());
            loginLog.setCreatedTime(new Date());
            loginLog.setUpdatedBy(loginUser.getUsername());
            loginLog.setUpdatedTime(new Date());
            loginLog.setRevision(0L);
            sysUserService.insertLoginLog(loginLog);
        } catch (Exception e) {
            logger.warn("系统登录日志保存失败，异常原因【{}】", e.getMessage());
        }

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(Rt.success(RtCodeEnum.R10006.getMessage())));
        out.flush();
        out.close();
    }
}
